class_name MovementEnemy
extends Enemy_Impl

@export var speed := 100.0
@export var attack_range := 30.0
@export var attack_delay := 1.0
@export var fresh_nav_delay := 0.5
@onready var nav_timer: Timer = %NavTimer
@onready var attack_timer: Timer = %AttackTimer
@onready var body_image: Node2D = %Body
@onready var animation_player: AnimationPlayer = $AnimationPlayer

var nav_path: PackedVector2Array = []
var current_path_index := 0
var is_hurt := false
var target_room: Room2D = null

func _ready():
	super()

func reset() -> void:
	super()
	nav_path = []
	current_path_index = 0

	nav_timer.timeout.connect(on_nav_timer_timeout)
	nav_timer.start(fresh_nav_delay)
	on_nav_timer_timeout()

	attack_timer.timeout.connect(on_attack_timer_timeout)
	attack_timer.start(attack_delay)
	animation_player.play("move")

func _physics_process(delta: float) -> void:
	super(delta)
	move()

func _on_attack(_enemy: Enemy_Impl) -> void:
	if attack_obj == null:
		return
	if attack_obj.has_method("hurt"):
		attack_obj.hurt()

func _on_hurt(_enemy: Enemy_Impl, hurt_dir: Vector2) -> void:
	# back when hurt
	if hurt_dir != Vector2.ZERO:
		is_hurt = true
		hurt_dir = hurt_dir.normalized()
		velocity = -hurt_dir * 300
		var tween = create_tween()
		tween.tween_property(self, "velocity", Vector2.ZERO, 0.5)
		tween.tween_callback(func(): is_hurt = false)
	pass

func _on_die(_enemy: Enemy_Impl) -> void:
	print("Test Enemy died")

func move() -> void:
	if not is_hurt:
		velocity = Vector2.ZERO
		var dir := calc_nav_dir()
		if dir != Vector2.ZERO:
			body_image.rotation = dir.angle() - PI * 0.5
			velocity = dir * speed
	move_and_slide()

func on_attack_timer_timeout() -> void:
	if attack_obj && (global_position - attack_obj.global_position).length() < 10:
		attack()

func on_nav_timer_timeout() -> void:
	_get_nav_path()

func _get_nav_path() -> void:
	if attack_obj == null:
		nav_path = []
		return
	nav_path = RoomManager.get_room_path_to_pos(self, attack_obj.global_position)
	current_path_index = 0

func calc_nav_dir() -> Vector2:
	if nav_path.size() == 0:
		return Vector2.ZERO
	var cur_target = nav_path[current_path_index]
	if (global_position - cur_target).length() < 10:
		current_path_index += 1
	
	if current_path_index < nav_path.size():
		cur_target = nav_path[current_path_index]
	else:
		current_path_index = nav_path.size() - 1
		return Vector2.ZERO
	
	return (cur_target - global_position).normalized()
